package com.joysuch.wwyt.bp.repository;

import com.joysuch.wwyt.bp.entity.investigate.BpInvestigateRecord;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;

import java.time.LocalDate;
import java.util.List;

/**
 * @Author ZhangDong
 * @Date 2020/3/25 16:24
 */
public interface BpInvestigateRecordRepository extends JpaRepository<BpInvestigateRecord, Long>, JpaSpecificationExecutor<BpInvestigateRecord> {


    List<BpInvestigateRecord> findByCheckPlanId(Long checkPlanId);

    BpInvestigateRecord findFirstByTaskIdAndSourceType(Long taskId,Integer sourceType);

    @Query(value = "select * from wwyt_bp_investigate_record where check_plan_id=:checkPlanId and check_user_id=:recordUserId " +
            "and delete_flag='0' order by id desc limit 1", nativeQuery = true)
    BpInvestigateRecord findByCheckPlanIdAndRecordUserId(Long checkPlanId, Long recordUserId);

    List<BpInvestigateRecord> findByCheckUserIdOrderByIdDesc(Long checkUserId);

    List<BpInvestigateRecord> findByCheckPlanIdAndCheckUserIdAndCheckFinishDate(Long checkPlanId, Long checkUserId, LocalDate checkFinishDate);

    @Query(value = "update BpInvestigateRecord i set i.deleteFlag='1' where i.id in :ids",nativeQuery = true)
    @Modifying
    void deleteByIds(@Param("ids") List<Long> ids);

    @Query(value = "select point.sign_in_method " +
            "from wwyt_bp_investigate_plan plan " +
            "         inner join wwyt_risk_hidden_danger_content hidden on plan.hidden_danger_content_id = hidden.id " +
            "         inner join wwyt_risk_point_business_evaluation_detail detail on detail.id = hidden.detail_id " +
            "         inner join wwyt_risk_point point on detail.risk_point_id = point.ID " +
            "where plan.id = ?1",nativeQuery=true)
    Integer getPointSingInMethodByPlanId(Long planId);

    @Query(value = "select record.* from wwyt_bp_investigate_record record inner join wwyt_bp_investigate_record_item item on item.record_id = record.id where item.id = ?1",nativeQuery = true)
    BpInvestigateRecord findByItemId(Long itemId);

    @Query("select checkPlanId from BpInvestigateRecord where id in (?1)")
    List<Long> findPlanIdByIdIn(List<Long> planId);

    List<BpInvestigateRecord> findAllByTaskIdIn(List<Long> taskIds);

}
